import axios from 'axios';
import { useTaskStore } from '@/stores/taskStore';

const API_BASE_URL = window.__env__.VITE_API_BASE_URL || 'http://127.0.0.1:8000/api/v1';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 上传DOI文件
export async function uploadDoiFile(file: File) {
  const taskStore = useTaskStore();
  const formData = new FormData();
  formData.append('file', file);
  
  // 添加客户端ID
  if (taskStore.clientId) {
    formData.append('client_id', taskStore.clientId);
  }
  
  try {
    const response = await axios.post(`${API_BASE_URL}/doi/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    
    return response.data;
  } catch (error) {
    console.error('上传文件错误:', error);
    throw error;
  }
}

// 获取任务状态
export async function fetchTaskStatus(taskId: string) {
  try {
    const response = await apiClient.get(`/doi/task/${taskId}/status`);
    return response.data;
  } catch (error) {
    console.error(`获取任务状态错误 (${taskId}):`, error);
    throw error;
  }
}

// 获取所有任务的最新状态
export async function fetchAllTasksStatus(taskIds: string[]) {
  return Promise.all(
    taskIds.map(async (taskId) => {
      try {
        const status = await fetchTaskStatus(taskId);
        return { taskId, status, success: true };
      } catch (error) {
        return { taskId, error, success: false };
      }
    })
  );
}

// 删除任务
export async function deleteTask(taskId: string) {
  try {
    const response = await apiClient.delete(`/doi/task/${taskId}`);
    return response.data;
  } catch (error) {
    console.error(`删除任务错误 (${taskId}):`, error);
    throw error;
  }
}

export async function deleteAllTasks(clientId: string, taskType: string = 'DOI') {
  try {
    const response = await apiClient.delete(`/doi/tasks/client/${clientId}?task_type=${taskType}`);
    return response.data;
  } catch (error) {
    console.error(`删除所有任务错误:`, error);
    throw error;
  }
}

// 获取客户端所有任务
// 获取客户端所有任务
export async function fetchClientTasks(clientId: string, taskType: string = 'DOI') {
  try {
    const response = await apiClient.get(`/doi/tasks/client/${clientId}?task_type=${taskType}`);
    return response.data;
  } catch (error) {
    console.error(`获取客户端任务错误 (${clientId}):`, error);
    throw error;
  }
}

// 直接输入DOI
export async function inputDois(doisText: string) {
  const taskStore = useTaskStore();
  
  try {
    const response = await apiClient.post('/doi/input', {
      dois: doisText,
      client_id: taskStore.clientId
    });
    
    return response.data;
  } catch (error) {
    console.error('提交DOI错误:', error);
    throw error;
  }
}

// 导出任务结果为Excel
export async function exportTaskResults(taskId: string) {
  try {
    // 使用window.open直接下载文件
    window.open(`${API_BASE_URL}/doi/task/${taskId}/export`, '_blank');
  } catch (error) {
    console.error(`导出任务结果错误 (${taskId}):`, error);
    throw error;
  }
}

// 导出任务结果到源文件
export async function exportToSourceFile(taskId: string) {
  try {
    // 使用window.open直接下载文件
    window.open(`${API_BASE_URL}/doi/task/${taskId}/export-to-source`, '_blank');
  } catch (error) {
    console.error(`导出到源文件错误 (${taskId}):`, error);
    throw error;
  }
}

// 下载任务的所有PDF文件
export async function downloadTaskPdfs(taskId: string) {
  try {
    // 使用window.open直接下载文件
    window.open(`${API_BASE_URL}/doi/task/${taskId}/download-pdfs`, '_blank');
  } catch (error) {
    console.error(`下载PDF文件错误 (${taskId}):`, error);
    throw error;
  }
}

// 提交JiangSu下载任务
export async function submitJiangSuUrl(url: string) {
  const taskStore = useTaskStore();
  
  try {
    const response = await apiClient.post('/doi/jiangsu', {
      url: url,
      client_id: taskStore.clientId
    });
    
    return response.data;
  } catch (error) {
    console.error('提交JiangSu URL错误:', error);
    throw error;
  }
}